﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml.XPath;

namespace GeoParser
{
	/// <summary>
	/// <see cref="Track"/>s are divided into segments.
	/// </summary>
	[Immutable]
	public class TrackSegment
	{
		private readonly XElement m_Element;

		public TrackSegment(XElement element)
		{
			if (element == null)
				throw new ArgumentNullException("element");
			m_Element = element;
		}
	
		public IEnumerable<TrackPoint> Points
		{
			get
			{
				return m_Element.Elements(m_Element.Name.Namespace + "trkpt")
					.Select(x => new TrackPoint(x));
			}
		}

		public Distance Length
		{
			get { return Distance.Length(Points.Cast<GeoPoint>()); }
		}

		public TimeSpan Time
		{
			get
			{
				return Points.Last().Time - Points.First().Time;
			}
		}

		public Distance LengthBetween(GeoPoint start, GeoPoint end)
		{
			return Distance.Length(Points.Cast<GeoPoint>()
				.SkipWhile(x => !GeoPoint.Equals(x, start))
				.TakeWhile(x => !GeoPoint.Equals(x, end)));
		}
	}
}